<!DOCTYPE html>
<html lang="en" xml:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <link rel="stylesheet" href="/layui/css/layui.css">
  <link rel="stylesheet" href="/css/custom.form.css">
</head>
<body>
<div class="panel panel-default operation_equipment" hidden>
  <div class="panel-heading title"></div>
  <div class="layui-card-body">
    <form class="layui-form layui-form-pane" action="" lay-filter="" style="width: 700px;margin-top: 10px">
      <input name="id" hidden/>
      <input name="pid" hidden/>
      <div class="layui-form-item">
        <label class="layui-form-label">设备名称</label>
        <div class="layui-input-block">
          <input type="text" name="equipmentName" placeholder="请输入设备名称" autocomplete="off" class="layui-input">
        </div>
      </div>
      <div class="layui-form-item">
        <label class="layui-form-label" for="pidName">上级设备</label>
        <div class="layui-input-block">
          <input type="text" id="pidName" name="pidName" placeholder="请选择上级控制设备" autocomplete="off" class="layui-input"
                 readonly="readonly" style="background:#eeeeee!important">
        </div>
      </div>
      <div class="layui-form-item">
        <label class="layui-form-label">传输协议</label>
        <div class="layui-input-inline" style="width: 180px;">
          <select name="transportProtocols" lay-verity="required" lay-filter="transportProtocols" class="select">
            <option value="1">tcp</option>
            <option value="2">mqtt</option>
          </select>
        </div>
      </div>

      <div class="layui-form-item">
        <label class="layui-form-label">禁用状态</label>
        <div class="layui-input-block">
          <input type="checkbox" name="isDisable" lay-skin="switch" lay-filter="switch" lay-text="启用|禁用" checked>
        </div>
      </div>
      <div class="layui-form-item">
        <div class="layui-input-block">
          <button type="submit" class="layui-btn" lay-submit="" lay-filter="submit">保存</button>
          <button class="layui-btn layui-btn-primary" id="btn_cancel">返回</button>
        </div>
      </div>
    </form>
  </div>
</div>
<!--加载设备树-->
<div id="equipmentTree" style="display: none"></div>
<!--加载设备列表-->
<div class="equipment-table">
  <table class="layui-table" id="equipmentTable" lay-filter="equipmentTable"></table>
</div>
</body>
<script type="text/html" id="toolbar">
  <div class="layui-btn-group">
    <button type="button" class="layui-btn" lay-event="addEquipment" shiro:hasPermission="sys:equipment:add">
      <i class="layui-icon">&#xe608;</i> 添加
    </button>
  </div>

</script>
<script type="text/html" id="tool">
  <a class="layui-btn layui-btn-xs" lay-event="edit" shiro:hasPermission="sys:equipment:update">编辑</a>
  <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del" shiro:hasPermission="sys:equipment:delete">删除</a>
</script>
<script src="/layui/layui.js"></script>
<script src="/js/core.util.js"></script>
<script>
  layui.config({
    base: '/'
  }).extend({
    treetable: 'treetable-lay/treetable'
  }).use(['treetable', 'jquery', 'form', 'tree', 'table'], function () {
    var treetable = layui.treetable;
    var tree = layui.tree;
    var form = layui.form;
    var table = layui.table;
    var $ = layui.jquery;
    /*树选中节点记录*/
    var selectNode = null;
    var loadDeptTreeTable = function () {
      CoreUtil.sendAjax("/api/equipments", null, function (res) {
        renderTable(res.data);
      }, "GET", false, function (res) {
        //无访问权限提示
        layer.msg("抱歉！您暂无此权限权限");
        var noAuthorityData = [];
        renderTable(noAuthorityData);
      });
    }
    //进入页面后触发此函数，加载部门数据列表
    loadDeptTreeTable();
    /*初始化部门列表数据*/
    var renderTable = function (data) {
      treetable.render({
        // 渲染表格
        data: data,
        treeColIndex: 1, // 树形图标显示在第几列
        treeSpid: 0, // 最上级的父级id
        treeIdName: 'id', // id字段的名称
        treePidName: 'pid', // pid字段的名称
        treeDefaultClose: false, // 是否默认折叠
        treeLinkage: true, // 父级展开时是否自动展开所有子级
        elem: '#equipmentTable', // 表格id
        page: false, // 树形表格一般是没有分页的
        toolbar: '#toolbar',
        cols: [
          [
            {type: 'numbers'},
            {field: 'id', title: 'ID'},
            {field: 'equipmentCode', title: '设备编码'},
            {field: 'equipmentName', title: '设备名称',},
            {
              field: 'pidName', title: '上级控制设备', templet: function (item) {
                if (item.pidName === null || item.pidName === undefined) {
                  return "最顶级设备";
                } else {
                  return item.pidName;
                }
              }
            },
            {field: 'relationCode', title: '层级关系编码'},
            {
              field: 'transportProtocols', title: '传输协议', templet: function (item) {
                return item.transportProtocols == '1' ? 'tcp' : "mqtt";
              }
            },
            {
              field: 'equipmentStatus', title: '设备在线状态', templet: function (item) {

                return item.equipmentStatus == '1' ? '在线' : '离线'
              }
            },
            {
              field: 'opened', title: '设备开启状态', templet: function (item) {
                if (item.pid != 0) {
                  var strCheck = item.opened == '1' ? 'checked' : '';
                  return ' <input type="checkbox" lay-skin="switch" lay-filter="opened" lay-text="开启|关闭" ' +
                    '' + strCheck + ' mid = ' + item.id + '&' + item.opened + ' shiro:hasPermission="sys:equipment:update">'
                } else {
                  return ' 主控设备 ';
                }
              }
            },
            {
              field: 'isDisable', title: '设备禁用状态', templet: function (item) {
                var strCheck = item.isDisable == '1' ? 'checked' : '';
                return ' <input type="checkbox" lay-skin="switch" lay-filter="isDisable" lay-text="启用|禁用" ' +
                  '' + strCheck + ' disabled>'
              }
            },
            {
              field: 'createTime', title: '创建时间', minWidth: 120, templet: function (item) {
                return CoreUtil.formattime(item.createTime);
              }
            },
            {title: '操作', width: 250, toolbar: '#tool'}
          ]
        ]
      });
    };

    //开启或关闭电机
    form.on('switch(opened)', function (obj) {
      var arr = $(this).attr("mid").split("&");
      var equipmentId = arr[0];
      var status = arr[1];
      var str = arr[1] == "1" ? "关闭" : "开启";
      var equipObj = {};
      equipObj.id = equipmentId;
      if (status == '1') {
        status = '0';
      } else {
        status = '1';
      }
      equipObj.opened = status;
      layer.open({
        content: '确定要' + str + '该设备吗' + "?",
        yes: function (index, layero) {
          layer.close(index); //如果设定了yes回调，需进行手工关闭
          CoreUtil.sendAjax("/api/equipment/changeSwitch", JSON.stringify(equipObj), function (res) {
            layer.msg(res.msg);
            loadDeptTreeTable();
          }, "PUT", false, function (res) {
            //无权限更新部门提示
            layer.msg("抱歉！您没有权限");
            loadDeptTreeTable();
          });
        }
      });
    });


    //点击添加时触发，此时初始化树
    var initTree = function (id) {
      var param = {deptId: id}
      CoreUtil.sendAjax("/api/equipment/tree", param, function (res) {
        loadDeptTree(res.data);
      }, "GET", false, function (res) {
        //无条件获取部门树提示
        layer.msg("抱歉！您没有权限");
        var noAuthorityData = [];
        loadDeptTree(noAuthorityData);
      });
    }
    //加载树数据
    var loadDeptTree = function (data) {
      //仅节点左侧图标控制收缩
      tree.render({
        elem: '#equipmentTree'
        , data: data
        , onlyIconControl: true  //是否仅允许节点左侧图标控制展开收缩
        , click: function (obj) {
          selectNode = obj;
          layer.msg(JSON.stringify(selectNode.data.title));
        }
      });
    };

    //新增设备事件
    table.on('toolbar(equipmentTable)', function (obj) {

      switch (obj.event) {
        case 'addEquipment':
          selectNode = null;
          //隐藏表格
          $(".equipment-table").hide();
          //显示编辑窗口
          $(".operation_equipment").show();
          $(".title").html("新增设备");
          $(".operation_equipment input[name=id]").val("");
          $(".operation_equipment input[name=pid]").val("");
          $(".operation_equipment input[name=equipmentName]").val("");
          $(".operation_equipment input[name=pidName]").val("");
          $(".operation_equipment select[name=transportProtocols]").val("1");

          $(".operation_equipment input[name=isDisable]").attr('checked', 'checked');
          $(".operation_equipment input[name=isDisable]").attr('type', 'hidden').val(1);
          var x = document.getElementsByClassName("layui-unselect layui-form-switch");
          x[0].setAttribute("class", "layui-unselect layui-form-switch layui-form-onswitch");
          var d = document.getElementsByTagName('em')[0];
          d.firstChild.nodeValue = '启用';
          form.render(); //更新全部
          initTree("");
          break;
      }
    });

    //打开树列表对话框
    $(".operation_equipment input[name=pidName]").click(function () {
      layer.open({
        type: 1,
        offset: '50px',
        skin: 'layui-layer-molv',
        title: "选择设备",
        area: ['400px', '550px'],
        shade: 0,
        shadeClose: false,
        content: $("#equipmentTree"),
        btn: ['确定', '取消'],
        yes: function (index) {
          if (selectNode.data != null) {
            //选中回显
            $(".operation_equipment input[name=pid]").val(selectNode.data.id);
            $(".operation_equipment input[name=pidName]").val(selectNode.data.title);
          }

          layer.close(index);
        }
      });
    });

    //监听指定开关
    form.on('switch(switch)', function () {
      $(".operation_equipment input[name=isDisable]").attr('type', 'hidden').val(this.checked ? 1 : 0);

    });

    //编辑或新增的界面取消事件
    $("#btn_cancel").click(function () {
      //隐藏表格
      $(".equipment-table").show();
      //显示编辑窗口
      $(".operation_equipment").hide();
      //可以防止在表单事件操作后自动刷新
      return false;
    });


    //监听提交
    form.on('submit(submit)', function (data) {
      //新增
      if (data.field.id === undefined || data.field.id === null || data.field.id === "") {
        CoreUtil.sendAjax("/api/equipment", JSON.stringify(data.field), function (res) {
          loadDeptTreeTable();
          //显示表格
          $(".equipment-table").show();
          //隐藏编辑窗口
          $(".operation_equipment").hide();
        }, "POST", false, function (res) {
          //无权限新增部门提示
          layer.msg("抱歉！您没有权限");
        });
      } else {
        CoreUtil.sendAjax("/api/equipment", JSON.stringify(data.field), function (res) {
          loadDeptTreeTable();
          //显示表格
          $(".equipment-table").show();
          //隐藏编辑窗口
          $(".operation_equipment").hide();
        }, "PUT", false, function (res) {
          //无条件更新部门提示
          layer.msg("抱歉！您没有权限");
        });
      }
      return false;
    });

    //操作项事件
    table.on('tool(equipmentTable)', function (obj) {
      var data = obj.data;
      switch (obj.event) {
        case 'edit':
          selectNode = null;
          //隐藏表格
          $(".equipment-table").hide();
          //显示编辑窗口
          $(".operation_equipment").show();
          $(".title").html("编辑设备");
          $(".operation_equipment input[name=id]").val(data.id);
          $(".operation_equipment input[name=pid]").val(data.pid);
          $(".operation_equipment input[name=equipmentName]").val(data.equipmentName);
          $(".operation_equipment input[name=pidName]").val(data.pidName);
          $(".operation_equipment select[name=transportProtocols]").val(data.transportProtocols);
          if (data.isDisable == 1) {
            $(".operation_equipment input[name=isDisable]").attr('checked', 'checked');
            $(".operation_equipment input[name=isDisable]").attr('type', 'hidden').val(1);
            var x = document.getElementsByClassName("layui-unselect layui-form-switch");
            x[0].setAttribute("class", "layui-unselect layui-form-switch layui-form-onswitch");
            var d = document.getElementsByTagName('em')[0];
            d.firstChild.nodeValue = '启用';
          } else {
            $(".operation_equipment input[name=isDisable]").attr('type', 'hidden').removeAttr("checked").val(0);
            var x = document.getElementsByClassName("layui-unselect layui-form-switch");
            x[0].setAttribute("class", "layui-unselect layui-form-switch");
            var d = document.getElementsByTagName('em')[0];
            d.firstChild.nodeValue = '禁用';
          }
          form.render(); //更新全部
          initTree(data.id);
          break;
        case 'del':
          // layer.msg("确定删除"+data.name);
          deletedEquipment(data.id, data.equipmentName);
          break;
      }
    });

    //删除操作
    var deletedEquipment = function (deptId, menuName) {
      layer.open({
        content: '确定要删除' + menuName + "?",
        yes: function (index, layero) {
          layer.close(index); //如果设定了yes回调，需进行手工关闭
          CoreUtil.sendAjax("/api/equipment/" + deptId, null, function (res) {
            layer.msg(res.msg);
            loadDeptTreeTable();
          }, "DELETE", false, function (res) {
            //无权限提示
            layer.msg("抱歉！您没有权限");
          });
        }
      });
    };

  });
</script>
</html>